package com.chuantou.yuba.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.chuantou.yuba.R;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.MultiPartRequest;
import com.chuantou.yuba.api.to.BaseTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.util.AccountManager;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.ImageUtil;
import com.chuantou.yuba.util.MediaUtil;
import com.chuantou.yuba.util.UiUtil;

/**
 * 举报界面
 * 
 * @author Administrator
 * 
 */
public class ReportActivity extends BaseActionBarActivity implements OnClickListener {
	public static final int REQUEST_CODE_LOCAL = 19;
	private EditText mInputView;
	private RecyclerView mRecyclerView;
	private ImageAdapter mAdapter;
	private Map<String, Bitmap> mBitmapCache = new HashMap<String, Bitmap>();
	private long mUid;
	private ProgressDialog mProgressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.report);
		mUid = getIntent().getLongExtra(Constants.EXTRA_UID, -1);
		setupViews();
		setTitle(R.string.report);
	}

	private void setupViews() {
		mInputView = (EditText) findViewById(R.id.content);
		mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
		LinearLayoutManager layoutManager = new LinearLayoutManager(this);
		layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
		mRecyclerView.setLayoutManager(layoutManager);
		mAdapter = new ImageAdapter();
		mRecyclerView.setAdapter(mAdapter);
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setMessage(getString(R.string.sending));
		mProgressDialog.setCancelable(false);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_submit, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_submit:
			if (UiUtil.isFastDoubleClick())
				return true;
			report();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onDestroy() {
		for (String key : mBitmapCache.keySet()) {
			mBitmapCache.get(key).recycle();
		}
		mBitmapCache.clear();
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.image:
			selectPicFromLocal();
			break;
		case R.id.delete:
			ImageView imageView = (ImageView) v;
			int position = Integer.parseInt(String.valueOf(imageView.getTag()));
			mAdapter.remove(position);
			break;
		default:
			break;
		}
	}

	private void report() {
		String inputText = mInputView.getText().toString().trim();
		if (TextUtils.isEmpty(inputText)) {
			Toast.makeText(getApplicationContext(), R.string.input_report_error, Toast.LENGTH_SHORT).show();
			return;
		}

		AccountManager accountManager = AccountManager.getInstance(getApplicationContext());
		if (!accountManager.isLogined()) {
			UiUtil.showNoLoginDialog(this, -1, LoginActivity.ACTION_RETURN);
			return;
		} else {
			UserTO user = accountManager.getUserTO();
			if (user.isExpired()) {
				Toast.makeText(this, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
				LoginActivity.start(this, -1, LoginActivity.ACTION_RETURN);
			} else {
				mProgressDialog.show();
				String url = UriHelper.getReportUrl();
				MultiPartRequest<BaseTO> request = new MultiPartRequest<BaseTO>(Method.POST, url, new Listener<BaseTO>() {

					@Override
					public void onResponse(BaseTO response) {
						if (!hasDestroyed()) {
							mProgressDialog.dismiss();
							if (response != null) {
								if (response.isSuccess()) {
									Toast.makeText(getApplicationContext(), R.string.operate_success, Toast.LENGTH_SHORT).show();
									onBackPressed();
								} else {
									if (response.getStatus() == BaseTO.STATUS_TOKEN_ERROR || response.getStatus() == BaseTO.STATUS_TOKEN_EXPIRED) {
										Toast.makeText(getApplicationContext(), R.string.message_token_expired, Toast.LENGTH_SHORT).show();
										LoginActivity.start(ReportActivity.this, -1, LoginActivity.ACTION_RETURN);
									} else {
										String msg = response.getMsg();
										msg = TextUtils.isEmpty(msg) ? getString(R.string.operate_failed) : msg;
										Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
									}
								}
							} else {
								Toast.makeText(getApplicationContext(), R.string.operate_failed, Toast.LENGTH_SHORT).show();
							}
						}
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						if (!hasDestroyed()) {
							mProgressDialog.dismiss();
							Toast.makeText(getApplicationContext(), R.string.request_error, Toast.LENGTH_SHORT).show();
						}
					}
				}, BaseTO.class);
				List<String> paths = mAdapter.getPaths();
				if (paths != null && !paths.isEmpty()) {
					for (int i = 0; i < paths.size(); i++) {
						request.addFileUpload("picture" + (i + 1), new File(paths.get(i)));
					}
				}
				request.addStringUpload(UriHelper.PARAMS_TOKEN, user.getToken());
				request.addStringUpload(UriHelper.PARAMS_PROF_UID, String.valueOf(mUid));
				request.addStringUpload(UriHelper.PARAMS_UID, String.valueOf(user.getUid()));
				request.addStringUpload(UriHelper.PARAMS_MESSAGE, inputText);
				RequestManager.startUpload(getApplicationContext(), request);
			}
		}
	}

	/**
	 * 从图库获取图片
	 */
	public void selectPicFromLocal() {
		Intent intent;
		if (Build.VERSION.SDK_INT < 19) {
			intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.setType("image/*");

		} else {
			intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		}
		startActivityForResult(intent, REQUEST_CODE_LOCAL);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case REQUEST_CODE_LOCAL:
				if (data != null) {
					Uri selectedImage = data.getData();
					if (selectedImage != null) {
						String path = MediaUtil.getPath(this, selectedImage);
						mAdapter.add(path);
						mAdapter.notifyDataSetChanged();
						mRecyclerView.getLayoutManager().scrollToPosition(mAdapter.getItemCount() - 1);
					}
				}
				break;
			default:
				break;
			}
		}
	}

	private class ImageAdapter extends RecyclerView.Adapter<ImageHolder> {
		private List<String> mPaths = new ArrayList<String>();
		int mMaxWidth = getResources().getDimensionPixelSize(R.dimen.send_trend_thumnail_width);

		public List<String> getPaths() {
			return mPaths;
		}

		@Override
		public int getItemCount() {
			if (mPaths.size() < 9) {
				return mPaths.size() + 1;
			} else {
				return mPaths.size();
			}
		}

		public void add(String path) {
			if (!mPaths.contains(path)) {
				mPaths.add(path);
			}
		}

		public void clear() {
			mPaths.clear();
			notifyDataSetChanged();
		}

		public void remove(int position) {
			mPaths.remove(position);
			mAdapter.notifyDataSetChanged();
		}

		@Override
		public void onBindViewHolder(ImageHolder holder, int position) {
			if (mPaths.size() < 9 && getItemCount() - 1 == position) {
				holder.getImageView().setImageResource(R.drawable.image_add);
				holder.mDeleteView.setVisibility(View.GONE);
				holder.getImageView().setOnClickListener(ReportActivity.this);
			} else {
				String path = mPaths.get(position);
				Bitmap bitmap = mBitmapCache.get(path);
				if (bitmap == null) {
					bitmap = ImageUtil.decodeSampledBitmapFromFile(path, mMaxWidth, mMaxWidth);
					if (bitmap != null) {
						mBitmapCache.put(path, bitmap);
					}
				}
				holder.getImageView().setImageBitmap(bitmap);
				holder.mDeleteView.setVisibility(View.VISIBLE);
				holder.getImageView().setOnClickListener(null);
			}
			holder.mDeleteView.setTag(position);
		}

		@Override
		public ImageHolder onCreateViewHolder(ViewGroup parent, int position) {
			View view = View.inflate(parent.getContext(), R.layout.image_item, null);
			return new ImageHolder(view);
		}

	}

	class ImageHolder extends RecyclerView.ViewHolder {
		private ImageView mImageView;
		private ImageView mDeleteView;

		public ImageHolder(View itemView) {
			super(itemView);
			mImageView = (ImageView) itemView.findViewById(R.id.image);
			mDeleteView = (ImageView) itemView.findViewById(R.id.delete);
			mDeleteView.setOnClickListener(ReportActivity.this);
		}

		public ImageView getImageView() {
			return mImageView;
		}
	}
}
